/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package dailydilbert;

import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author sarcoex
 */
public class Dilbert {

    public String image = "";
    public String html  = "dilbert.hml";

    public Dilbert(String htmlOut) {
        if (htmlOut != null)
            this.html = htmlOut;
    }

    public Dilbert() {
        
    }

    public void getDaily() {

        String HTML_S = "<html>";
        String HTML_E = "</html>";
        String HEAD_S = "<head>";
        String HEAD_E = "</head>";
        String BODY_S = "<body>";
        String BODY_E = "<body>";

        String REFRESH = "<meta http-equiv=\"refresh\" content=\"600\">";

        String httpImage = "<div class=\"STR_Image\">";
        String dilbertImage = "src=\"/dyn/str_strip/";
        String dilbertAlt = "\" alt=\"";
        String http = "";
        String s = "";
        InputStream is;
        DataInputStream dis;
        try {
            URL u = new URL("http://www.dilbert.com/strips/");
            is = u.openStream();
            dis = new DataInputStream(new BufferedInputStream(is));
            while ((s = dis.readLine()) != null) {
                http += s;
            }

            dis.close();
            is.close();

            http = http.substring(http.indexOf(httpImage));
            http = http.substring(http.indexOf(dilbertImage));
            http = http.replaceAll("src=\"", "");
            http = http.substring(0, http.indexOf(dilbertAlt));
            http = http.replaceFirst("/", "");

            String exImage = "http://www.dilbert.com/" + http;

            String internalHtml = "<img src=\"" + exImage + "\" >";

            String HTML =
                    HTML_S +
                    HEAD_S +
                    REFRESH +
                    HEAD_E +
                    BODY_S +
                    internalHtml +
                    BODY_E +
                    HTML_E;

            FileWriter writer = new FileWriter(this.html);
            writer.write(HTML);
            writer.flush();
            writer.close();

            this.image = exImage;
        }
        catch (IOException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
